<?php

namespace app\admin\controller;


use app\common\model\CommonModel;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Exception;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/12/23
 * Time: 15:28
 */
class Login extends controller
{

    public function index()
    {
        try {

            if (request()->isAjax()) {
                $param = input('param.');
                $sql = Db::table('cms_blog_admin')->where('username', $param['username'])->column('id,username,password');
                if (empty($sql)) {
                    return ['code' => 0, 'msg' => '用户名不存在'];
                }
                foreach ($sql as $res) {
                    $password = (new CommonModel())->thinkDecrypt($res['password']);
                    if ($res['username'] == $param['username'] && $password == $param['password']) {
                        $token = $this->makeToken();
                        $data = [
                            'token' => $token,
                            'login_time' => time() + 604800 //token7天后过期
                        ];
                        $update = Db::table('cms_blog_admin')->where('id', $res['id'])->update($data);
                        if ($update) {
                            Cookie::set('token', $token);
                            return ['code' => 1, 'msg' => '登录成功', 'url' => 'index'];
                        }
                    } else {
                        return ['code' => 0, 'msg' => '用户名或者密码错误'];
                    }
                }
            }
            return $this->fetch();
        } catch (\Exception $e) {
            echo $e->getMessage() . '.............' . $e->getFile() . '..............' . $e->getLine();
        }
    }


    private function makeToken()
    {
        $str = md5(uniqid(md5(microtime(true)), true)); //生成一个不会重复的字符串
        $str = sha1($str); //加密
        return $str;
    }


}